package spe.ui.wizard;

import java.io.ByteArrayInputStream;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

/**
 * 	@author Dao Anh Vu
 *  @since 1.0
 * 
 */
public class DiagramNewWizard extends Wizard implements INewWizard 
{
	public static final String ID = DiagramNewWizard.class.getName();
	private DiagramNewWizardPage mainPage;
	private IStructuredSelection selection;
	
	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		// TODO Auto-generated method stub
		setWindowTitle("New Method Plugin");
		this.selection = selection;
	}
	
	@Override
	public void addPages()
	{
		mainPage = new DiagramNewWizardPage();
		addPage(mainPage);
		mainPage.init(selection);
	}

	@Override
	public boolean performFinish() 
	{
		try{
			IFolder folder = mainPage.getLibraryFolder();
			IFile diagramFile = folder.getFile(String.format("%s.dg", mainPage.getDiagramName()));
			diagramFile.create(createDefaultDiagram(folder), true, null);
			
			IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
			IWorkbenchPage activePage = window.getActivePage();
			
			IDE.openEditor(activePage, diagramFile);
		}catch(CoreException ce)
		{
			
		}
		return false;
	}
	
	private ByteArrayInputStream createDefaultDiagram(IFolder folder)
	{
		String parName = folder.getName();
		String processName = parName; //.substring(0, parName.indexOf(".par"));
		StringBuffer buffer = new StringBuffer();
		buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		buffer.append("\n");
		buffer.append("<diagram  name=\"" + processName + "\"></diagram>");	
		return new ByteArrayInputStream(buffer.toString().getBytes());
	}
}
